package sk.ygor.raynor.client.http;

import com.google.gwt.json.client.JSONValue;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;

public class HttpPostJSONServiceResult {

    public static final String RESULT = "OK";
    public static final String EXCEPTION = "EX";

    private String type;

    private JSONValue result;

    private String exceptionMessage;

    public HttpPostJSONServiceResult(JSONValue parsedResponse) {
        JSONObject jsonObject = parsedResponse.isObject();
        if (jsonObject == null) {
            throw new HttpPostJSONServiceException("Response must be a JSONObject");
        }
        this.type = extractString(jsonObject, "type");
        if (this.type.equals(EXCEPTION)) {
            this.exceptionMessage = extractString(jsonObject, "exceptionMessage");
        } else {
            this.result = jsonObject.get("result");
        }
    }

    private String extractString(JSONObject jsonObject, String propertyName) {
        JSONValue propertyAsJSONValue = jsonObject.get(propertyName);
        if (propertyAsJSONValue == null) {
            throw new HttpPostJSONServiceException("Response JSONObject must have a property '" + propertyName + " of type JSONString");
        }
        JSONString propertyAsJSONString = propertyAsJSONValue.isString();
        if (propertyAsJSONString == null) {
            throw new HttpPostJSONServiceException("Response JSONObject must have a property '" + propertyName + " of type JSONString");
        }
        return propertyAsJSONString.stringValue();
    }


    public String getType() {
        return type;
    }

    public JSONValue getResult() {
        return result;
    }

    public String getExceptionMessage() {
        return exceptionMessage;
    }

    @Override
    public String toString() {
        return "HttpPostJSONServiceResult{" +
                "type='" + type + '\'' +
                ", result=" + result +
                ", exceptionMessage='" + exceptionMessage + '\'' +
                '}';
    }
}
